var express = require('express');
var router = express.Router();

let connection = require('../base/ConnUtil').getConn();

/**
 * 所有表格名称
 */
router.get('/', function (req, res, next) {
  let email = req.query.email;
  const sql = `SELECT * FROM user_account_content WHERE email = '${email}'`;
  connection.query(sql, function (error, results, fields) {
    if (error) {
      console.log(error);
      res.send({
        code: 500,
        msg: error.sqlMessage
      });
      return;
    };
    console.log(sql, results.length);

    res.send(results);
  });
});

router.post('/', function (req, res, next) {
  let body = req.body;
  const sql = `SELECT * FROM user_account_content WHERE email = '${body.email}' and operType = '${body.operType}'`;
  connection.query(sql, function (error, results, fields) {
    if (error) {
      console.log(error);
      res.send({
        code: 500,
        msg: error.sqlMessage
      });
      return;
    };
    console.log(sql, results.length);

    if (results.length === 0) {
      const insertSql = `insert into user_account_content (email, operType, content) 
      values ('${body.email}', '${body.operType}', '${body.content}')`;
      connection.query(insertSql, function (error, results, fields) {
        if (error) {
          console.log(error);
          res.send({
            code: 500,
            msg: error.sqlMessage
          });
          return;
        };
        console.log(insertSql, results.length);
        res.send(results);
      });
    } else {
      const updateSql = `update user_account_content set content = '${body.content}' 
      where email = '${body.email}' and operType = '${body.operType}'`;
      connection.query(updateSql, function (error, results, fields) {
        if (error) {
          console.log(error);
          res.send({
            code: 500,
            msg: error.sqlMessage
          });
          return;
        };
        console.log(updateSql, results.length);
        res.send(results);
      });
    }
  });
});

module.exports = router;
